package com.java.comprehensive.arithmetic.programmers;

import cn.hutool.core.util.ArrayUtil;

/**
 * @Author: 窦绍飞
 * @Date: 2022/6/6
 */
public class SetZeroes {
	public static void setZeroes(int[][] matrix) {
		int length = matrix.length;
		int length_2 = matrix[0].length;
		boolean[] l = new boolean[length];
		boolean[] r = new boolean[length_2];
		for (int i = 0; i < length; i++) {
			for (int i1 = 0; i1 < length_2; i1++) {
				if (matrix[i][i1] == 0) {
					l[i] = true;
					r[i1] = true;
				}
			}
		}
		for (int i = 0; i < l.length; i++) {
			for (int i1 = 0; i1 < r.length; i1++) {
				if (l[i] || r[i1]) {
					matrix[i][i1] = 0;
				}
			}
		}
	}

	public static void setZeroes_2(int[][] matrix) {
		int m = matrix.length, n = matrix[0].length;
		boolean flagCol0 = false, flagRow0 = false;
		for (int i = 0; i < m; i++) {
			if (matrix[i][0] == 0) {
				flagCol0 = true;
			}
		}
		for (int j = 0; j < n; j++) {
			if (matrix[0][j] == 0) {
				flagRow0 = true;
			}
		}
		for (int i = 1; i < m; i++) {
			for (int j = 1; j < n; j++) {
				if (matrix[i][j] == 0) {
					matrix[i][0] = matrix[0][j] = 0;
				}
			}
		}
		for (int i = 1; i < m; i++) {
			for (int j = 1; j < n; j++) {
				if (matrix[i][0] == 0 || matrix[0][j] == 0) {
					matrix[i][j] = 0;
				}
			}
		}
		if (flagCol0) {
			for (int i = 0; i < m; i++) {
				matrix[i][0] = 0;
			}
		}
		if (flagRow0) {
			for (int j = 0; j < n; j++) {
				matrix[0][j] = 0;
			}
		}
	}


	public static void main(String[] args) {
//		[[0,1,2,0],[3,4,5,2],[1,3,1,5]]
		int[][] matrix = {{0, 1, 2, 0},
				{3, 4, 5, 2},
				{1, 3, 1, 5}};
		setZeroes_2(matrix);
		System.out.println(ArrayUtil.toString(matrix));
	}
}
